package com.woniuxy.pxxt.service.impl;

import com.woniuxy.pxxt.common.result.Result;
import com.woniuxy.pxxt.common.vo.test.TestVo;
import com.woniuxy.pxxt.dao.OptionDao;
import com.woniuxy.pxxt.dao.TestDao;
import com.woniuxy.pxxt.entity.Option;
import com.woniuxy.pxxt.service.OptionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 包含对应的选择题的选项(Option)表服务实现类
 *
 * @author makejava
 * @since 2022-03-07 16:28:52
 */
@Service
public class OptionServiceImpl implements OptionService {
    @Autowired(required = false)
    private OptionDao optionDao;

    @Autowired(required = false)
    private TestDao testDao;

    @Override
    @Transactional
    public Result addOptiones(TestVo test) {


        //执行添加试题方法
        testDao.addTest(test.getTest());
        //获取试题对应的培训名称
        // testDao.updateTestTrainId(test.getTrainName(),test.getTest().getTestName());

        //分隔选择的答案
        char[] chars = test.getTest().getAnswerIds().toCharArray();

        int addNum = 0;
        //添加试题答案 获得id
        //optionDao.addOptiones(test,test.());
        StringBuffer answerds = new StringBuffer();
        for (int i = 0; i < test.getOptiones().size(); i++) {
            Option option = test.getOptiones().get(i);
            option.setTrainId(test.getTest().getId());
            optionDao.addOptiones(option);


            if( addNum < chars.length && (chars[addNum]-'0'  == (char)i+1)){
                if (addNum == 0) {
                    answerds.append(+option.getId());
                }else {
                    answerds.append("," + option.getId());
                }
                addNum++;
            }
        }
        int num = testDao.updateTestById(test.getTest().getId(),answerds.toString());
        if(num > 0){
            return Result.ok().message("添加成功");
        }else {
            return Result.fail().message("稍后再试");

        }


    }

    @Override
    public Result deleteOptionesByTestId(Integer testId) {
        if (optionDao.deleteOptionesByTestId(testId) > 0) {
            return Result.ok();
        }

        return Result.fail();
    }

    @Override
    public Result findOptionesByTestId(Option option) {
        List<Option> optionList = optionDao.findOptionesByTestId(option);
        return Result.ok(optionList);
    }


}